package com.imooc.trading_system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.imooc.trading_system.enums.BizCodeEnum;
import com.imooc.trading_system.mapper.ProductMapper;
import com.imooc.trading_system.model.ProductDO;
import com.imooc.trading_system.model.UserDO;
import com.imooc.trading_system.service.ProductService;
import com.imooc.trading_system.service.UserService;
import com.imooc.trading_system.utils.JsonData;
import com.imooc.trading_system.vo.product.*;
import com.imooc.trading_system.vo.tradingHall.TradingHallSearchProductListReqVO;
import com.imooc.trading_system.vo.tradingHall.TradingHallSearchProductListRespVO;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import net.coobird.thumbnailator.Thumbnails;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author Feng zhaoxi
 * @since 2022-04-24
 */
@Service
public class ProductServiceImpl implements ProductService {
    @Autowired
    private UserService userService;
    @Resource
    private ProductMapper productMapper;

    @Value("${minio.endpointUrl}")
    public String endpointUrl;

    @Value("${minio.accessKey}")
    public String accessKey;

    @Value("${minio.secretKey}")
    public String secretKey;

    @Value("${minio.bucketName}")
    public String bucketName;

    /**
     * 上传产品图片
     *
     * @param file
     * @return
     */
    @Override
    public JsonData uploadProductImg(MultipartFile file) {
        try {
            //压缩图片
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            Thumbnails.of(file.getInputStream())
                    .scale(0.5)
                    .outputQuality(0.5f)
                    .toOutputStream(outputStream);
            byte[] bytes = outputStream.toByteArray();
            InputStream inputStream = new ByteArrayInputStream(bytes);
            MultipartFile newFile = new MockMultipartFile(file.getOriginalFilename(), file.getOriginalFilename(), file.getContentType(), inputStream);

            // 使用MinIO服务的URL，端口，Access key和Secret key创建一个MinioClient对象
            MinioClient minioClient = MinioClient.builder()
                    .endpoint(endpointUrl)
                    .credentials(accessKey, secretKey)
                    .build();

            // 检查存储桶是否已经存在
            boolean isExist = minioClient.bucketExists(BucketExistsArgs.builder().bucket(bucketName).build());
            if (isExist) {
                System.out.println("Bucket already exists.");
            } else {
                // 创建一个名为asiatrip的存储桶，用于存储照片的zip文件。
                minioClient.makeBucket(MakeBucketArgs.builder()
                        .bucket(bucketName)
                        .build());
            }

            // 文件名字
            String fileName = "product_img/" + System.currentTimeMillis() + UUID.randomUUID();
            // 上传文件 已经文件大小
            // file.getContentType() 文件类型
            minioClient.putObject(
                    PutObjectArgs.builder().bucket(bucketName).object(fileName).stream(
                                    newFile.getInputStream(), newFile.getSize(), -1)
                            .contentType(newFile.getContentType())
                            .build());

            // 返回文件访问路径
            String url = endpointUrl + "/" + bucketName + "/" + fileName;
            return JsonData.buildSuccess(url);
        } catch (Exception e) {
            return JsonData.buildError("失败");
        }
    }

    /**
     * 上传产品详情图片
     *
     * @param file
     * @param product_id
     * @return
     */
    @Override
    public JsonData uploadProductDetailImg(MultipartFile file, int product_id) {
        return null;
    }

    /**
     * 发布产品
     *
     * @param publishProductReqVO
     * @return
     */
    @Override
    public JsonData publishProduct(PublishProductReqVO publishProductReqVO) {
        //获取登录用户
        UserDO userDO = userService.getLoginUser();
        //产品实例
        ProductDO productDO = new ProductDO();
        productDO.setPublishUserId(userDO.getId());
        BeanUtils.copyProperties(publishProductReqVO, productDO);
        List<String> detailImgList = publishProductReqVO.getProductImg().subList(1, publishProductReqVO.getProductImg().size());
        String detailImgListString = String.join(",", detailImgList);
        productDO.setProductCoverImg(publishProductReqVO.getProductImg().get(0));
        productDO.setProductDetailImg(detailImgListString);
        productDO.setProductStatus(publishProductReqVO.getProductStatus());
        int rows = productMapper.insert(productDO);
        if (rows == 1) {
            return JsonData.buildSuccess();
        } else {
            return JsonData.buildResult(BizCodeEnum.PUBLISH_PRODUCT_FAILED);
        }
    }

    /**
     * 获取产品列表
     *
     * @param searchProductListReqVO
     * @return
     */
    @Override
    public JsonData getProductList(SearchProductListReqVO searchProductListReqVO) {
        UserDO userDO = userService.getLoginUser();
        int page = searchProductListReqVO.getPage();
        int size = searchProductListReqVO.getSize();
        if (page > 0 && size > 0) {
            PageHelper.startPage(page, size);
        }
        searchProductListReqVO.setPublishUserId(userDO.getId());
        List<SearchProductListRespVO> list = productMapper.selectProductList(searchProductListReqVO);
        PageInfo<SearchProductListRespVO> pageInfo = new PageInfo<>(list);
        return JsonData.buildSuccess(pageInfo);
    }

    /**
     * 根据id获取产品详情
     *
     * @param getProductDetailReqVO
     * @return
     */
    @Override
    public JsonData getProductDetail(GetProductDetailReqVO getProductDetailReqVO) {
        ProductDO productDO = productMapper.selectOne(new QueryWrapper<ProductDO>()
                .eq("product_id", getProductDetailReqVO.getProductId()));
        if (productDO == null) {
            return JsonData.buildResult(BizCodeEnum.GET_PRODUCT_FAILED);
        } else {
            GetProductDetailRespVO getProductDetailRespVO = new GetProductDetailRespVO();
            BeanUtils.copyProperties(productDO, getProductDetailRespVO);
            List<String> productDetailImage = new ArrayList<>();
            productDetailImage.add(productDO.getProductCoverImg());
            List<String> list = Arrays.asList(productDO.getProductDetailImg().split(","));
            productDetailImage.addAll(list);
            getProductDetailRespVO.setProductDetailImage(productDetailImage);
            UserDO publishUserDO = userService.getPublishUserInfo(productDO.getPublishUserId());
            getProductDetailRespVO.setUniversity(publishUserDO.getUniversity());
            getProductDetailRespVO.setPublishUserName(publishUserDO.getUser());
            getProductDetailRespVO.setPublishUserImg(publishUserDO.getHeadImg());
            return JsonData.buildSuccess(getProductDetailRespVO);
        }
    }

    /**
     * 根据产品id获取产品实例
     *
     * @param productId
     * @return
     */
    @Override
    public ProductDO getProductInstance(int productId) {
        return productMapper.selectOne(new QueryWrapper<ProductDO>()
                .eq("product_id", productId));
    }

    /**
     * 产品下架
     *
     * @param getProductDetailReqVO
     * @return
     */
    @Override
    public JsonData downShelves(GetProductDetailReqVO getProductDetailReqVO) {
        ProductDO productDO = productMapper.selectOne(new QueryWrapper<ProductDO>()
                .eq("product_id", getProductDetailReqVO.getProductId()));
        UpdateWrapper<ProductDO> updateWrapper = new UpdateWrapper<>();
        updateWrapper.eq("product_id", getProductDetailReqVO.getProductId());
        productDO.setProductStatus(0);
        productMapper.update(productDO, updateWrapper);
        return JsonData.buildSuccess();
    }

    /**
     * 市场查询产品
     *
     * @param tradingHallSearchProductListReqVO
     * @return
     */
    @Override
    public JsonData searchProductList(TradingHallSearchProductListReqVO tradingHallSearchProductListReqVO) {
        List<ProductDO> productDOS = productMapper.tradingHallSearch(tradingHallSearchProductListReqVO);
        System.out.println("productDOS:" + productDOS);
        List<TradingHallSearchProductListRespVO> list = productDOS.stream().map(obj -> {
            TradingHallSearchProductListRespVO productListRespVO = new TradingHallSearchProductListRespVO();
            BeanUtils.copyProperties(obj, productListRespVO);
            return productListRespVO;
        }).collect(Collectors.toList());
        return JsonData.buildSuccess(list);
    }
}
